<?php
class ProjectsController extends AppController
{
    public $name = 'Projects';
    public $uses = array(
        'Project',
        'EmailTemplate',
    	'ProjectFund',
    	'Payment',
    );
    public $components = array(
        'RequestHandler',
        'Email'
    );
    public $helpers = array(
        'Embed'
    );
    public function beforeFilter()
    {
        $this->Security->disabledFields = array(
            'Attachment.filename',
            'ProjectReward',
            'Project.is_agree_terms_conditions',
            'Project.step',
			'Project.address',
			'Project.latitude',
			'Project.longitude',
			'Project.country_id',
			'City.name',
			'State.name',
			'Project.type',
			'Project.user_id',
            'City.id',
            'State.id',
        );
        parent::beforeFilter();
        if (!Configure::read('suspicious_detector.is_enabled') || !Configure::read('Project.auto_suspend_project_on_system_flag')) {
            $this->Project->Behaviors->detach('SuspiciousWordsDetector');
        }
    }
    public function index()
    {
        if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'home') {
            $this->pageTitle = __l('Home');
        } else {
            $this->pageTitle = __l('Projects');
        }
        $heading = __l('Projects');
        $limit = 20;
        $this->_redirectGET2Named(array(
            'city',
            'name',
            'q'
        ));
        $order = array(
            'Project.project_funding_end_date' => 'asc'
        );
        $conditions = array();
		$this->request->data['Project']['city'] = isset($this->request->params['named']['city']) ? $this->request->params['named']['city'] : '';
		if(empty($this->request->data['Project']['q'])){
			$this->request->data['Project']['q'] = isset($this->request->params['named']['q']) ? $this->request->params['named']['q'] : '';
		}
		$this->request->data['Project']['name'] =  isset($this->request->params['named']['name']) ? $this->request->params['named']['name'] : '';

        if (!empty($this->request->data['Project']['q'])) {
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->data['Project']['q']);
            $heading.= sprintf(__l(' - Search - %s') , $this->request->data['Project']['q']);
            $order = array(
                'Project.created' => 'DESC'
            );
        }
        $conditions['Project.is_active'] = 1;
        $conditions['Project.admin_suspend'] = '0';
		$view = '';
	if(Configure::read('Project.is_enable_idea') && ((!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'home') || (!empty($this->request->data['Project']['type']) && $this->request->data['Project']['type'] == 'idea'))){
			  $view = '1';
			  
			  $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForIdea;
			   $order = array(
					'Project.total_ratings' => 'desc'
				);
		        $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
	            $limit = 20;
		}else{
			$conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
			$conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
			$conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::GoalReached;
		}
        // city wise filtering
        if (!empty($this->request->data['Project']['city']) && $this->request->data['Project']['city']!='all' ) {
            $cityConditions = array();
            if (!empty($this->request->data['Project']['city'])) {
                $cityConditions['City.slug'] = $this->request->params['named']['city'];
            }
            $find_city = $this->Project->City->find('first', array(
                'conditions' => $cityConditions,
                'fields' => array(
                    'City.id',
                    'City.slug',
                    'City.name',
                    'Country.name',
                ) ,
                'recursive' => 0
            ));
            if (!Configure::read('site.is_enable_geo_location')) {
                $this->pageTitle.= ' - ' . __l('City') . ' - ' . $find_city['City']['name'] . ', ' . $find_city['Country']['name'];
                $heading.= ' - ' . __l('City') . ' - ' . $find_city['City']['name'] . ', ' . $find_city['Country']['name'];
            }else{
				  if (!empty($this->request->params['named']['type']) and $this->request->params['named']['type'] == 'home') {
				   $this->pageTitle= __l('Projects in ') . $find_city['City']['name'];
				  }
			}
            $conditions['Project.city_id'] = $find_city['City']['id'];
            $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
        }
        if (!empty($this->request->data['Project']['city'])) {
                $cityConditions['City.slug'] = $this->request->params['named']['city'];
                if(!Configure::read('Project.is_enable_idea'))
                {
                    $conditions['Project.project_status_id'] = array(ConstProjectStatus::OpenForFunding,ConstProjectStatus::ReserveAmountReached);
                }
                else
               {
                   $conditions['Project.project_status_id'] = array(ConstProjectStatus::OpenForFunding,ConstProjectStatus::OpenForIdea,ConstProjectStatus::ReserveAmountReached);
               }
            }
		 if (!empty($this->request->data['Project']['city']) && $this->request->data['Project']['city']=='all' ) {
             $cityConditions = array();
             $cityConditions['City.is_approved'] = 1;
            $find_city = $this->Project->City->find('list', array(
                'conditions' => $cityConditions,
                'fields' => array(
                    'City.id',
                ) ,
                'recursive' => 0
            ));
            $conditions['Project.city_id'] = $find_city;
		 }
	 if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'myprojects') {
            unset($conditions['Project.city_id']);
            if (!$this->Auth->user('id')) {
                throw new NotFoundException(__l('Invalid request'));
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'pending') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::Pending;
            }
           if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'idea') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForIdea;
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'open_for_funding') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'cancelled') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::ProjectCancelled;
				unset($conditions['Project.project_funding_end_date >= ']);
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'expired') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::FundingExpired;
				unset($conditions['Project.project_funding_end_date >= ']);
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'closed') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::FundingClosed;
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'goal') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::GoalReached;
            }
            if (!empty($this->request->params['named']['status']) && $this->request->params['named']['status'] == 'reserve_amount_reached') {
                $conditions['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
            }
            $statuses = $this->Project->ProjectStatus->find('list', array(
                'conditions' => array(
                    'ProjectStatus.is_active' => 1
                )
            ));
            $count = $this->Project->find('count', array(
                'conditions' => array(
                    'Project.is_active' => 1,
                    'Project.user_id' => $this->Auth->user('id')
                )
            ));
            $projectStatuses = array();
            foreach($statuses as $key => $status) {
                $status_condition = array(
                        'Project.project_status_id ' => $key,
                        'Project.user_id' => $this->Auth->user('id')
                    );
                if($key!= ConstProjectStatus::ProjectCancelled)
                {
                  $status_condition['Project.is_active'] = 1;
                }
                $project_status = $this->Project->find('count', array(
                    'conditions' => $status_condition
                ));
                $projectStatuses[$key] = $project_status;
            }
            $this->set('projectStatuses', $projectStatuses);
            $this->set('count', $count);
            $this->pageTitle.= ' - ' . __l('User') . ' - ' . $this->Auth->user('username');
            $this->pageTitle.= ' - ' . __l('My Projects');
            $heading = __l('My Projects');
            $conditions['Project.user_id'] = $this->Auth->user('id');
            unset($conditions['Project.admin_suspend']);
            unset($conditions['Project.is_active']);
            unset($conditions['NOT']);
        } else {
            $conditions['Project.project_status_id !='] = ConstProjectStatus::ProjectCancelled;
        }
        // Featured filtering
        $discover_heading = '';
        if (!empty($this->request->params['named']['filter'])) {
			unset($conditions['OR']);
            switch ($this->request->params['named']['filter']) {
            case 'recommended':
                $this->pageTitle.= ' - ' . __l('Recommended');
                $heading.= ' - ' . __l('Recommended');
                $discover_heading.= __l('New &amp; Noteworthy');
                $conditions['Project.is_recommended'] = 1;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::GoalReached;
                $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
                $order = array(
                    'Project.project_funding_end_date' => 'asc'
                );
                break;

            case 'popular':
                $this->pageTitle.= ' - ' . __l('Popular');
                $heading.= ' - ' . __l('Popular');
                $discover_heading.= __l('Popular This Week');
                $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::GoalReached;
                $order = array(
                    'Project.project_view_count' => 'DESC'
                );
                break;

            case 'almost_funded':
                $this->pageTitle.= ' - ' . __l('Almost Funded');
                $heading.= ' - ' . __l('Almost Funded');
                $conditions['Project.project_status_id != '] = ConstProjectStatus::FundingClosed;
                $conditions['Project.collected_percentage >= '] = Configure::read('Project.almost_funded_percentage');
                $conditions['AND']['Project.collected_percentage < '] = 100;
                $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
                $order = array(
                    'Project.collected_percentage' => 'DESC'
                );
                break;

            case 'ending_soon':
                $this->pageTitle.= ' - ' . __l('Ending Soon');
                $heading.= ' - ' . __l('Ending Soon');
                $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::OpenForFunding;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::ReserveAmountReached;
                $conditions['OR'][]['Project.project_status_id'] = ConstProjectStatus::GoalReached;
                $order = array(
                    'Project.project_funding_end_date' => 'ASC',
                    'Project.collected_percentage' => 'DESC'
                );
                break;

            case 'small_projects':
                $this->pageTitle.= ' - ' . __l('Small Projects');
                $heading.= ' - ' . __l('Small Projects');
                $conditions['Project.project_status_id'] = array(ConstProjectStatus::OpenForFunding, ConstProjectStatus::ReserveAmountReached);
                $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
                $conditions['OR']['Project.needed_amount <= '] = Configure::read('Project.small_project_max_amount');
                $conditions['OR']['TO_DAYS(Project.project_funding_end_date) - TO_DAYS(Project.project_funding_start_date) <= '] = Configure::read('Project.small_project_max_days');
                break;

            case 'hall_of_fame':
                $this->pageTitle.= ' - ' . __l('Hall of Fame');
                $heading.= ' - ' . __l('Hall of Fame');
                $conditions['Project.project_status_id'] = ConstProjectStatus::FundingClosed;
                $order = array(
                    'Project.collected_amount' => 'DESC'
                );
                break;

            case 'successful':
                $this->pageTitle.= ' - ' . __l('Successful');
                $heading.= ' - ' . __l('Successful');
                $discover_heading.= __l('Recently Successful');
                $conditions['Project.project_status_id'] = ConstProjectStatus::FundingClosed;
                $order = array(
                    'Project.project_fund_goal_reached_date' => 'DESC'
                );
                break;
            }
        }
        // category wise filtering
        if (!empty($this->request->params['named']['category'])) {
            $category = $this->Project->ProjectCategory->find('first', array(
                'conditions' => array(
                    'ProjectCategory.slug' => $this->request->params['named']['category']
                ) ,
                'fields' => array(
                    'ProjectCategory.id',
                    'ProjectCategory.name',
                ) ,
                'recursive' => - 1
            ));
            $this->pageTitle.= ' - ' . __l('Category') . ' - ' . $category['ProjectCategory']['name'];
            $heading.= ' - ' . __l('Category') . ' - ' . $category['ProjectCategory']['name'];
            $conditions['Project.project_category_id'] = $category['ProjectCategory']['id'];
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'funding') {
            $this->pageTitle = __l('Home - Projects For Funding');
            $heading = __l('Projects For Funding');
            $order = array(
                'Project.project_funding_end_date' => 'asc'
            );
			//$limit = 4;
        }
		 if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'funding' && !empty($this->request->params['named']['view']) && $this->request->params['named']['view'] == 'home') {
            $this->pageTitle = __l('Home - Projects For Funding');
            $heading = __l('Projects For Funding');
            $order = array(
                'Project.project_funding_end_date' => 'asc'
            );
			$limit = 4;
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'funding-closed') {
            $this->pageTitle.= ' - ' . __l('Funding closed');
            $heading = __l('Funding Closed Projects');
			unset($conditions['OR']);
            $conditions['Project.project_status_id'] = ConstProjectStatus::FundingClosed;
            $order = array(
                'Project.project_funding_end_date' => 'asc'
            );
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'closed') {
            $this->pageTitle.= ' - ' . __l('Closed/Cancelled');
            $heading = __l('Closed Projects');
			unset($conditions['OR']);
            unset($conditions['Project.project_status_id !=']);
            $conditions['Project.project_status_id'] = ConstProjectStatus::ProjectCancelled;
            $order = array(
                'Project.project_funding_end_date' => 'asc'
            );
        }
        // condition for elememt in user view page
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'userview') {
            unset($conditions['Project.city_id']);
			unset($conditions['OR']);
            if (!empty($this->request->params['named']['cat']) && $this->request->params['named']['cat'] == 'myprojects') {
                $conditions['Project.user_id'] = $this->request->params['named']['user'];
                $conditions['Project.project_status_id NOT'] = array(
					                                        ConstProjectStatus::Pending,
					                                        ConstProjectStatus::OpenForIdea);
            }else if (!empty($this->request->params['named']['cat']) && $this->request->params['named']['cat'] == 'ideaproject') {
                $conditions['Project.user_id'] = $this->request->params['named']['user'];
                $conditions['Project.project_status_id'] = ConstProjectStatus::OpenForIdea;
				$view =1;
                unset($conditions['Project.admin_suspend']);
            }elseif (!empty($this->request->params['named']['cat']) && $this->request->params['named']['cat'] == 'fundedptojects') {
                $funds = $this->Project->ProjectFund->find('all', array(
                    'conditions' => array(
                        'OR' => array(
                            array(
                                'ProjectFund.is_paid' => 1
                            ) ,
                            array(
                                'ProjectFund.is_paid' => 0
                            ) ,
                        ) ,
                        'ProjectFund.user_id' => $this->request->params['named']['user'],
                        'ProjectFund.is_cancelled' => 0,
                        'ProjectFund.is_refunded' => 0
                    ) ,
                    'fields' => array(
                        'ProjectFund.project_id'
                    ) ,
                ));
                $project_ids = array();
                foreach($funds as $fund) {
                    array_push($project_ids, $fund['ProjectFund']['project_id']);
                }
                $project_ids = array_unique($project_ids);
                $conditions['Project.id'] = $project_ids;
				unset($conditions['Project.project_funding_end_date >= ']);
            } elseif (!empty($this->request->params['named']['cat']) && $this->request->params['named']['cat'] == 'followingprojects') {
                $followings = $this->Project->ProjectFollower->find('all', array(
                    'conditions' => array(
                        'ProjectFollower.user_id' => $this->request->params['named']['user']
                    ) ,
                    'fields' => array(
                        'ProjectFollower.project_id'
                    ) ,
                    'recursive' => - 1
                ));
                $project_ids = array();
                foreach($followings as $following) {
                    array_push($project_ids, $following['ProjectFollower']['project_id']);
                }
                $project_ids = array_unique($project_ids);
                $conditions['Project.id'] = $project_ids;
            } elseif (!empty($this->request->params['named']['cat']) && $this->request->params['named']['cat'] == 'ratedprojects') {
                $ratings = $this->Project->ProjectRating->find('all', array(
                    'conditions' => array(
                        'ProjectRating.user_id' => $this->request->params['named']['user']
                    ) ,
                    'fields' => array(
                        'ProjectRating.project_id'
                    ) ,
                    'recursive' => - 1
                ));
                $project_ids = array();
                foreach($ratings as $rating) {
                    array_push($project_ids, $rating['ProjectRating']['project_id']);
                }
                $project_ids = array_unique($project_ids);
                $conditions['Project.id'] = $project_ids;
            }
        }
        $this->set('heading', $heading);
        if (!empty($discover_heading)) {
            $this->set('discover_heading', $discover_heading);
        }
		
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'home') {
		
            $conditions['Project.project_funding_end_date >= '] = date('Y-m-d');
            $limit = 4;
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'myprojects' && empty($this->request->params['named']['filter'])) {
            unset($conditions['Project.project_status_id !=']);
			unset($conditions['OR']);
        }
         if ($this->RequestHandler->isRss()) {
            $order = array(
                'Project.project_funding_end_date' => 'desc'
            );
         }
        if (!empty($this->request->data['Project']['q'])) {
            $conditions['Project.name like '] = '%' . $this->request->data['Project']['q'] . '%';
            $limit = 20;
        }
        $this->paginate = array(
            'conditions' => $conditions,
            'contain' => array(
			    'ProjectFollower' => array(
					'conditions' => array(
						'ProjectFollower.user_id' => $this->Auth->user('id') ,
					) ,
					'fields' => array(
						'ProjectFollower.id',
						'ProjectFollower.user_id',
						'ProjectFollower.project_id'
					)
				),
                'ProjectStatus' => array(
                    'fields' => array(
                        'ProjectStatus.id',
                        'ProjectStatus.name'
                    )
                ) ,
                'ProjectReward',
                'ProjectCategory' => array(
                    'fields' => array(
                        'name',
                        'slug'
                    )
                ) ,
                'User' => array(
                    'UserAvatar',
                    'fields' => array(
                        'User.username',
                        'User.id'
                    )
                ) ,
                'Country' => array(
                    'fields' => array(
                        'Country.name',
                        'Country.iso2'
                    )
                ) ,
                'City' => array(
                    'fields' => array(
                        'City.name',
                        'City.slug'
                    )
                ) ,
				'Message'=>array(
					'conditions'=>array(
							'Message.is_sender'=>'0',
							'Message.user_id'=>$this->Auth->user('id'),

						),
				),
                'Attachment',
                'Transaction',
				'ProjectRating'=>array(
					'conditions'=>array(
						'ProjectRating.user_id'=>$this->Auth->user('id'),
					),
				),
            ) ,
            'fields' => array(
                'DATEDIFF(Project.project_funding_end_date,now()) as enddate',
                'Project.id',
                'Project.created',
                'Project.modified',
                'Project.name',
                'Project.description',
                'Project.short_description',
                'Project.user_id',
                'Project.project_category_id',
                'Project.project_status_id',
                'Project.needed_amount',
                'Project.project_funding_start_date',
                'Project.project_funding_end_date',
                'Project.collected_amount',
                'Project.reserve_amount',
                'Project.commission_amount',
                'Project.collected_percentage',
                'Project.total_ratings',
                'Project.project_rating_count',
                'Project.project_view_count',
                'Project.project_fund_count',
                'Project.project_follower_count',
                'Project.project_comment_count',
                'Project.blog_count',
                'Project.message_count',
                'Project.slug',
                'Project.is_active',
                'Project.ip_id',
                'Project.is_recommended',
                'Project.is_allow_over_funding',
                'Project.video_embed_url',
                'Project.admin_suspend',
                'Project.is_system_flagged',
                'Project.detected_suspicious_words',
                'Project.reserve_reached_date',
                'Project.project_fund_goal_reached_date',
                'Project.project_cancelled_date',
                'Project.project_feed_count',
				'Project.actual_rating',
				'Project.feed_url'
            ) ,
            'order' => $order,
            'recursive' => 3,
            'limit' => $limit,
        );

		if ($this->RequestHandler->prefers('json')) {
		
			$this->paginate = array(
            'conditions' => $conditions,
			'contain' => array(

                'Attachment' => array(
					'fields' =>array(
						'Attachment.id',
						'Attachment.filename',
						'Attachment.dir',
						'Attachment.width',
						'Attachment.height',
						'Attachment.thumb'
						
					)
				),
				'ProjectCategory' => array(
                    'fields' => array(
                        'ProjectCategory.id',
                        'ProjectCategory.name',
                        'ProjectCategory.slug'
                    )
                ) ,
				'User' => array(
					'fields' => array(
						'User.username',
						'User.id'
					)
				),
				
                'Country' => array(
                    'fields' => array(
                        'Country.name',
                        'Country.iso2'
                    )
                ) ,
                'City' => array(
                    'fields' => array(
                        'City.name',
                        'City.slug'
                    )
                ) ,
                
			
            ) ,
            'fields' => array(
                
                'Project.id',
                'Project.name',
                'Project.project_funding_end_date',
                'Project.collected_amount',
                'Project.reserve_amount',
                'Project.collected_percentage',
				'Project.needed_amount',
                'Project.slug',
				
				
				
            ) ,
            'order' => $order,
            'recursive' => 3,
           'limit' => $limit,
       		);	
		    $iphone_project_index=$this->paginate();
			$total_project_count = $this->Project->find('count', array(
            'conditions' => $conditions,
            'recursive' => 0
        	));
			
			for($end=0;$end<count($iphone_project_index);$end++)
			{   
			    $image_options = array(
            			'dimension' => 'iphone_project_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				$image_url = Router::url('/', true).$this->Project->getImageUrl('Project', $iphone_project_index[$end]['Attachment'], $image_options);
				
				$big_image_options = array(
            			'dimension' => 'iphone_project_big_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				$big_thumb_image_url = Router::url('/', true).$this->Project->getImageUrl('Project', $iphone_project_index[$end]['Attachment'], $big_image_options);
				
				if(strtotime($iphone_project_index[$end]['Project']['project_funding_end_date']) < strtotime(date('Y-m-d')))
				{
					$month = date('F',strtotime($iphone_project_index[$end]['Project']['project_funding_end_date']));
					$year = date('y',strtotime($iphone_project_index[$end]['Project']['project_funding_end_date']));
					$days_to_go = $month." ".$year;
					$text = "Funded";
				}
				else
				{
					$days_to_go = (strtotime($iphone_project_index[$end]['Project']['project_funding_end_date'])-strtotime(date('Y-m-d')))/(60*60*24);
					$text = "Days to go";
				}
				
				//$project_descrption = 'A'.' '.$iphone_project_index[$end]['ProjectCategory']['name'].' '.'Project'.' '.'in by'.' '.$iphone_project_index[$end]['User']['username'];
				
				$backer = $this->Project->ProjectFund->find('count', array(
            		'conditions' => array(
               			 'OR' => array(
                    			array(
                        			'ProjectFund.is_paid' => 1
                   				 ) ,
                    			array(
                        			'ProjectFund.is_paid' => 0
                    			) ,
                		) ,
               		 'ProjectFund.project_id' => $iphone_project_index[$end]['Project']['id'],
               		 'ProjectFund.is_failed' => 0,
                	 'ProjectFund.is_refunded' => 0
           	 		) ,
            	'recursive' => - 1
        		));
				
				if((strtotime($iphone_project_index[$end]['Project']['project_funding_end_date']) < strtotime(date('Y-m-d'))) && ($iphone_project_index[$end]['Project']['needed_amount']!=$iphone_project_index[$end]['Project']['collected_amount']))
				{
					$project_status = -1;
				}
				else if($iphone_project_index[$end]['Project']['needed_amount']==$iphone_project_index[$end]['Project']['collected_amount'])
				{
					$project_status = 1;
				}
				else
				{
					$project_status = 0;
				}
				$follower = $this->Project->ProjectFollower->find('first', array(
            		'conditions' => array(
                	'ProjectFollower.user_id' => $this->Auth->user('id') ,
                	'ProjectFollower.project_id' => $iphone_project_index[$end]['Project']['id']
            		) ,
            		'fields' => array(
                	'ProjectFollower.id',
                	'ProjectFollower.user_id',
                	'ProjectFollower.project_id'
           		 	) ,
            		'recursive' => - 1
       			 ));
			
				if(!empty($follower))
				{
					$follw_status = 0;
					//$follw_url="project_followers/delete/".$follower['ProjectFollower']['id'];
					$follower_action_id=$follower['ProjectFollower']['id'];
				}
				else if(empty($follower))
				{
					$follw_status = 1;
					//$follw_url="project_followers/add/".$iphone_project_index[$end]['Project']['id'];
					$follower_action_id=$iphone_project_index[$end]['Project']['id'];
				}
				
				if($iphone_project_index[$end]['User']['id']==$this->Auth->user('id'))
				{
					$own_project=1;
				}
				else
				{
					$own_project=0;
				}
				if($this->Auth->user('id'))
				{
					$follow_session_status=1;
				} 
				else
				{
					$follow_session_status=0;
				}
				$iphone_project_indexs[$end]['Project_id'] = $iphone_project_index[$end]['Project']['id'];
				$iphone_project_indexs[$end]['Project_name'] = $iphone_project_index[$end]['Project']['name'];
				$iphone_project_indexs[$end]['Project_slug'] = $iphone_project_index[$end]['Project']['slug'];
				$iphone_project_indexs[$end]['Pledged'] = $iphone_project_index[$end]['Project']['collected_amount'];
				$iphone_project_indexs[$end]['Funding_amount'] = $iphone_project_index[$end]['Project']['needed_amount'];
				$iphone_project_indexs[$end]['Funded'] = ($iphone_project_index[$end]['Project']['collected_percentage']!="")?$iphone_project_index[$end]['Project']['collected_percentage']:0.00;
				$iphone_project_indexs[$end]['Progress_bar_percentage'] = ($iphone_project_index[$end]['Project']['collected_percentage']!="")?$iphone_project_index[$end]['Project']['collected_percentage']:0.00;
				$iphone_project_indexs[$end]['Project_image_url'] = $image_url;
				$iphone_project_indexs[$end]['Days_to_go'] = $days_to_go;
				$iphone_project_indexs[$end]['Days_to_go_text'] = __l($text);
				
				$iphone_project_indexs[$end]['Backers'] = $backer;
				$iphone_project_indexs[$end]['Category_id'] = $iphone_project_index[$end]['ProjectCategory']['id'];
				$iphone_project_indexs[$end]['Category_name'] = $iphone_project_index[$end]['ProjectCategory']['name'];
				$iphone_project_indexs[$end]['Project_username'] = $iphone_project_index[$end]['User']['username'];
				$iphone_project_indexs[$end]['Project_country'] = $iphone_project_index[$end]['Country']['name'];
				$iphone_project_indexs[$end]['Project_city'] = $iphone_project_index[$end]['City']['name'];
				$iphone_project_indexs[$end]['Project_status'] = $project_status;
				$iphone_project_indexs[$end]['Project_big_thumb_image_url'] = $big_thumb_image_url;
				$iphone_project_indexs[$end]['Project_follower_status'] = $follw_status;
				$iphone_project_indexs[$end]['Project_follower_action_id'] = $follower_action_id;
				$iphone_project_indexs[$end]['Own_project_flag'] = $own_project;
				$iphone_project_indexs[$end]['Project_follow_session'] = $follow_session_status;
				$iphone_project_indexs[$end]['total_page'] = ceil($total_project_count/20);
                $iphone_project_indexs[$end]['current_page'] = !empty($this->request->params['named']['page']) ? $this->request->params['named']['page'] : 1;
			}
			
			$this->view = 'Json';
			$this->set('json',$iphone_project_indexs);
	}
        $this->set('projects', $this->paginate());

			if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'myprojects') {
				$this->autoRender = false;
				$this->render('myprojects');
			}else if(!empty($this->request->query['ext']) && $this->request->query['ext'] =='rss'){
				$this->autoRender = false;
				$this->render('index');
				}else if($view){
				$this->autoRender = false;
				$this->render('index_list');
			}else if(!empty($this->request->params['named']['view']) && $this->request->params['named']['view'] == 'home'){
				$this->autoRender = false;
				$this->render('index_compact');
			}else if(Configure::read('Project.project_layout') == ConstViewLayout::CompactView){
				$this->autoRender = false;
				$this->render('project_compact');
			}

    }
    public function discover()
    {
        $this->pageTitle = __l('Browse');
    }
    public function view($slug = null, $view = null)
    {
        $this->pageTitle = __l('Project');
        if (is_null($slug)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $condition['Project.is_active'] = 1;
        $condition['Project.slug'] = $slug;


        $funded_users = $this->Project->ProjectFund->find('count', array(
            'contain' => array(
                'Project' ),
            'conditions' => array(
                             'ProjectFund.user_id'=> $this->Auth->user('id'),
                             'Project.slug'=> $slug,
                             ),
          'recursive' => 0,
        ));

        $project_detail_condition['Project.slug'] = $slug;
        $project_detail = $project = $this->Project->find('first', array(
            'conditions' => $project_detail_condition,
        ));

        if ($this->Auth->user('user_type_id') == ConstUserTypes::Admin || $funded_users || $this->Auth->user('id') == $project_detail['Project']['user_id']) {
            unset($condition['Project.is_active']);
        }
         $project = $project = $this->Project->find('first', array(
            'conditions' => $condition,
            'contain' => array(
                'ProjectStatus' => array(
                    'fields' => array(
                        'ProjectStatus.id',
                        'ProjectStatus.name'
                    )
                ) ,
                'ProjectCategory' => array(
                    'fields' => array(
                        'ProjectCategory.id',
                        'ProjectCategory.name',
                        'ProjectCategory.slug'
                    )
                ) ,
                'ProjectReward'=>array(
					'order'=>array(
						'ProjectReward.pledge_amount'=>'asc'
					)
				),
                'User' => array(
                    'UserAvatar',
                    'UserProfile' => array(
                        'Country' => array(
                            'fields' => array(
                                'Country.name',
                                'Country.iso2'
                            )
                        ) ,
                        'City' => array(
                            'fields' => array(
                                'City.name',
                                'City.slug'
                            ) ,
                        ) ,
                    ) ,
                    'UserWebsite' => array(
                        'fields' => array(
                            'UserWebsite.id',
                            'UserWebsite.website'
                        )
                    ) ,
                    'fields' => array(
                        'User.username',
                        'User.id',
						'User.project_count',
						'User.project_fund_count',
						'User.project_follower_count',
                    )
                ) ,
                'Country' => array(
                    'fields' => array(
                        'Country.name',
                        'Country.iso2'
                    )
                ) ,
                'City' => array(
                    'fields' => array(
                        'City.name',
                        'City.slug'
                    )
                ) ,
                'ProjectRating' => array(
                    'fields' => array(
                        'ProjectRating.user_id'
                    ) ,
                    'conditions' => array(
                        'ProjectRating.user_id' => $this->Auth->user('id')
                    )
                ) ,
                'Attachment',
				'ProjectMedia',
            ) ,
            'fields' => array(
                'DATEDIFF(Project.project_funding_end_date,now()) as enddate',
                'Project.id',
                'Project.created',
                'Project.modified',
                'Project.name',
                'Project.description',
                'Project.short_description',
                'Project.user_id',
                'Project.project_category_id',
                'Project.project_status_id',
                'Project.needed_amount',
				'Project.reserve_amount',
				'Project.project_funding_start_date',
                'Project.project_funding_end_date',
                'Project.collected_amount',
                'Project.collected_percentage',
                'Project.total_ratings',
                'Project.project_rating_count',
                'Project.project_view_count',
                'Project.project_fund_count',
                'Project.project_comment_count',
                'Project.blog_count',
                'Project.slug',
                'Project.is_active',
                'Project.is_active',
                'Project.ip_id',
                'Project.is_recommended',
                'Project.is_allow_over_funding',
                'Project.video_embed_url',
                'Project.admin_suspend',
                'Project.is_system_flagged',
                'Project.detected_suspicious_words',
                'Project.project_follower_count',
                'Project.linkedin_url',
                'Project.facebook_url',
                'Project.twitter_url',
                'Project.youtube_url',
                'Project.myspace_url',
                'Project.website_url',
                'Project.imdb_url',
                'Project.pledge_type_id',
                'Project.feed_url',
                'Project.facebook_feed_url',
                'Project.twitter_feed_url',
                'Project.project_feed_count',
                'Project.actual_rating',
            ) ,
            'recursive' => 4,
        ));



        if (empty($project)) {
            throw new NotFoundException(__l('Invalid request'));
        }

        $project_rating_count = $this->Project->ProjectRating->find('first', array(
            'conditions' => array(
                'ProjectRating.project_id' => $project['Project']['id'] ,
                'ProjectRating.user_id' => $this->Auth->user('id') ,
                ) ,
            'fields' => array(
                'ProjectRating.project_id',
            )
        ));
        $this->set('project_rating_count', $project_rating_count);
        
        if (($project['Project']['is_active'] == 0 || $project['Project']['admin_suspend'] == 1) && ($this->Auth->user('id') != $project['Project']['user_id']) && $this->Auth->user('user_type_id') != ConstUserTypes::Admin && (!$funded_users)) {
			if (!empty($project['Project']['admin_suspend'])) {
				$this->Session->setFlash(__l('Admin was suspended this project.') , 'default', null, 'error');
				$this->redirect(array(
					'controller' => 'projects',
					'action' => 'index',
					'type' => 'home'
				));
			}
            throw new NotFoundException(__l('Invalid request'));
        }
		if(($project['Project']['project_status_id'] == ConstProjectStatus::Pending || $project['Project']['project_status_id'] == ConstProjectStatus::FundingExpired || $project['Project']['project_status_id'] == ConstProjectStatus::ProjectCancelled || $project['Project']['project_status_id'] == ConstProjectStatus::RefundedDueToCancelled) && $this->Auth->user('id') != $project['Project']['user_id'] && (!$funded_users) && $this->Auth->user('user_type_id') != ConstUserTypes::Admin ) {
			throw new NotFoundException(__l('Invalid request'));
		}
        if (!empty($project['Project']['name'])) {
            Configure::write('meta.project_name', $project['Project']['name']);
        }
        if (!empty($project['Attachment'])) {
            $image_options = array(
                'dimension' => 'normal_medium_thumb',
                'class' => '',
                'alt' => $project['Project']['name'],
                'title' => $project['Project']['name'],
                'type' => 'png'
            );
            $project_image = Router::url('/', true) . $this->Project->getImageUrl('Project', $project['Attachment'], $image_options);
            Configure::write('meta.project_image', $project_image);
        }
        $follower = $this->Project->ProjectFollower->find('first', array(
            'conditions' => array(
                'ProjectFollower.user_id' => $this->Auth->user('id') ,
                'ProjectFollower.project_id' => $project['Project']['id']
            ) ,
            'fields' => array(
                'ProjectFollower.id',
                'ProjectFollower.user_id',
                'ProjectFollower.project_id'
            ) ,
            'recursive' => - 1
        ));
		
        $this->set('follower', $follower);
        $backer = $this->Project->ProjectFund->find('count', array(
            'conditions' => array(
                'OR' => array(
                    array(
                        'ProjectFund.is_paid' => 1
                    ) ,
                    array(
                        'ProjectFund.is_paid' => 0
                    ) ,
                ) ,
                'ProjectFund.project_id' => $project['Project']['id'],
                'ProjectFund.is_failed' => 0,
                'ProjectFund.is_refunded' => 0
            ) ,
            'recursive' => - 1
        ));
		if ($this->RequestHandler->prefers('json')) {
				
				$image_options = array(
            			'dimension' => 'iphone_project_big_thumb',
            			'class' => '',
            			'alt' => 'alt',
            			'title' => 'title',
            			'type' => 'jpg'
        		);
				$image_url = Router::url('/', true).$this->Project->getImageUrl('Project', $project['Attachment'], $image_options);
				
				if(strtotime($project['Project']['project_funding_end_date']) < strtotime(date('Y-m-d')))
				{
					$month = date('F',strtotime($project['Project']['project_funding_end_date']));
					$year = date('y',strtotime($project['Project']['project_funding_end_date']));
					$days_to_go = $month." ".$year;
					$text = "Funded";
				}
				else
				{
					$days_to_go = (strtotime($project['Project']['project_funding_end_date'])-strtotime(date('Y-m-d')))/(60*60*24);
					$text = "Days to go";
				} 
				$iphone_project_view['Project_id'] =  $project['Project']['id'];
				$iphone_project_view['Project_name'] =  $project['Project']['name'];
				$iphone_project_view['Project_category'] =  $project['ProjectCategory']['name'];
				$iphone_project_view['Project_category_slug'] =  $project['ProjectCategory']['slug'];
				$iphone_project_view['Username'] =  $project['User']['username'];
				$iphone_project_view['Backers'] =   $backer;
				$iphone_project_view['Project_image_url'] = $image_url;
				$iphone_project_view['Days_to_go'] = $days_to_go;
				$iphone_project_view['Days to go text'] = __l($text);
				$iphone_project_view['Funding_amount'] = $project['Project']['collected_amount'];
				$iphone_project_view['Circle_graph_percentage'] = $project['Project']['collected_percentage'];
				$iphone_project_view['Needed_amount'] = $project['Project']['needed_amount'];

				$this->view = 'Json';
				$this->set('json',$iphone_project_view);
		}
        $this->set('backer', $backer);
        $this->Project->ProjectView->create();
        $this->request->data['ProjectView']['project_id'] = $project['Project']['id'];
        $this->request->data['ProjectView']['user_id'] = $this->Auth->user('id');
        if ($view == 'widget') {
            $this->request->data['ProjectView']['project_view_type_id'] = ConstViewType::EmbedView;
        } else {
            $this->request->data['ProjectView']['project_view_type_id'] = ConstViewType::NormalView;
        }
		$this->request->data['ProjectView']['ip_id'] = $this->Project->ProjectView->toSaveIp();
		$this->Project->Behaviors->detach('Logable');
        $this->Project->ProjectView->save($this->request->data);
        Configure::write('meta.keywords', 'Pledge, ' . $project['ProjectCategory']['name']);
        Configure::write('meta.description', 'Funding for ' . $project['Project']['name']);
        $project_title = $project['Project']['name'];
        $this->pageTitle.= ' - ' . $project_title;
        $project['Project']['project_funding_end_date'] = $project['Project']['project_funding_end_date'] . ' 23:59:59';
        $this->set('project', $project);
        if (!empty($view)) {
            if ($view == 'widget') {
                $this->layout = 'embed';
            }
            $this->render($view);
        }
    }
    
	public function clear_cache() {
        Cache::clear();
        clearCache();

        $files = array();
        $files = array_merge($files, glob(CACHE . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'css' . DS . '*')); // remove cached css
        $files = array_merge($files, glob(CACHE . 'js' . DS . '*'));  // remove cached js           
        $files = array_merge($files, glob(CACHE . 'models' . DS . '*'));  // remove cached models           
        $files = array_merge($files, glob(CACHE . 'persistent' . DS . '*'));  // remove cached persistent           

        foreach ($files as $f) {
            if (is_file($f)) {
                unlink($f);
            }
        }

        if(function_exists('apc_clear_cache')):      
        apc_clear_cache();
        apc_clear_cache('user');
        endif;

        $this->set(compact('files'));
        $this->layout = 'ajax';
        $this->render(false);
    }    
    
    public function add()
    {
		if(Configure::read('Project.is_enable_idea')) {
			$this->pageTitle = __l('Add Idea');
        }
		else{
			$this->pageTitle = __l('Add Project');
		}
        $step = 1;
        $userProfile = array();
        $userProjectCount = $this->Project->find('all', array(
            'conditions' => array(
                'YEAR(Project.created)' => date('Y') ,
                'Project.user_id' => $this->Auth->user('id') ,
            ) ,
            'group' => 'Project.user_id',
            'fields' => array(
                'count(*) as count',
            ) ,
            'recursive' => - 1
        ));
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin && !empty($userProjectCount) && $userProjectCount['0']['0']['count'] >= Configure::read('Project.maximun_projects_per_user_per_year')) {
            $this->Session->setFlash(__l('Your allowed project quota is over for this year.') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'dashboard',
            ));
        }
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
            $remaining_project_count = Configure::read('Project.maximun_projects_per_user_per_year');
            if (!empty($userProjectCount)) {
                $remaining_project_count = Configure::read('Project.maximun_projects_per_user_per_year') - $userProjectCount['0']['0']['count'];
            }
            $this->set('remaining_project_count', $remaining_project_count);
        }
        
        if (!empty($this->request->data)) {
            $step = $this->request->data['Project']['step'];
            if (!empty($this->request->data['Project']['pledge_type_id']) && $this->request->data['Project']['pledge_type_id'] == ConstPledgeTypes::Any) {
                unset($this->request->data['Project']['min_amount_to_fund']);
            }
            if(!Configure::read('Project.is_enable_threshold_limit') && isset($this->request->data['Project']['needed_amount']))
            {
              $this->request->data['Project']['reserve_amount'] = $this->request->data['Project']['needed_amount'];
            }
            $this->Project->set($this->request->data);
            
            if ($this->Project->validates() || $step == 2) {
                $step = 2;
                 if (!empty($this->request->data['ProjectMedia'])) {
                                 for($i = 0 ; $i < 5 ; $i++ ) {
                                 if ($this->request->data['ProjectMedia'][$i]['filename']['error'] == 1) {
                                    $attachmentValidationError[$i] = sprintf(__l('The file uploaded is too big, only files less than %s permitted') , ini_get('upload_max_filesize'));
                                    $is_form_valid = false;
                                    continue;
                                 }
								 
                                 if (!empty($this->request->data['ProjectMedia'][$i]['filename']['tmp_name'])) {
                                     $image_info = getimagesize($this->request->data['ProjectMedia'][$i]['filename']['tmp_name']);
                                     $this->request->data['ProjectMedia']['filename'] = $this->request->data['ProjectMedia'][$i]['filename'];
                                     $this->request->data['ProjectMedia']['filename']['type'] = $image_info['mime'];
                                     $this->Project->ProjectMedia->Behaviors->attach('ImageUpload', Configure::read('project.file'));
                                     $this->Project->ProjectMedia->set($this->request->data);
                                 if (!$this->Project->validates() |!$this->Project->ProjectMedia->validates()) {
                                     $attachmentValidationError[$i] = $this->Project->ProjectMedia->validationErrors;
                                     $is_form_valid = false;
                                     $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
                                    }
                                  }

                                  }
                }

                                if (!empty($attachmentValidationError)) {
                                   foreach($attachmentValidationError as $key => $error) {
                                     $this->Project->ProjectMedia->validationErrors[$key]['filename'] = $error;
                                   }
                                }
                $this->Project->Attachment->Behaviors->attach('ImageUpload', Configure::read('Project.image'));
                $this->request->data['Project']['user_id'] = !empty($this->request->data['Project']['user_id']) ? $this->request->data['Project']['user_id'] : $this->Auth->user('id');
                $userProfile = $this->Project->User->UserProfile->find('first', array(
                    'conditions' => array(
                        'UserProfile.user_id' => $this->request->data['Project']['user_id'],
                    ) ,
                    'contain' => array(
                        'City' => array(
                            'fields' => array(
                                'City.name',
                                'City.id',
                            ) ,
                        ) ,
                        'State' => array(
                            'fields' => array(
                                'State.name',
                                'State.id',
                            ) ,
                        ) ,
                        'Country' => array(
                            'fields' => array(
                                'Country.name',
                                'Country.id',
                                'Country.iso2',
                            ) ,
                        ) ,
                        'User' => array(
                            'fields' => array(
                                'User.username',
                            ) ,
                        ) ,
                    ) ,
                    'recursive' => 0
                ));
                if (($this->request->data['Project']['step'] == 2)) {
                    if (!empty($this->request->data['Attachment']['filename']['name'])) {
                        $this->request->data['Attachment']['filename']['type'] = get_mime($this->request->data['Attachment']['filename']['tmp_name']);
                    }
                    if (!Configure::read('Project.image.allowEmpty')) {
                        $this->Project->Attachment->set($this->request->data);
                    }
                    if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
                        $this->request->data['Project']['is_active'] = 1;
                        $this->request->data['Project']['project_status_id'] = ConstProjectStatus::Pending;
						if ((!Configure::read('Project.listing_fee')) and Configure::read('Project.is_enable_idea')) {
							$this->request->data['Project']['project_status_id'] = ConstProjectStatus::OpenForIdea;
						}else{
							if ((!Configure::read('Project.listing_fee')) and Configure::read('Project.is_auto_approve')) {
								if(Configure::read('Project.is_enable_idea')){
								  $this->request->data['Project']['project_status_id'] = ConstProjectStatus::OpenForIdea;
								}
								else{
								  $this->request->data['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
								}
								$this->request->data['Project']['project_funding_start_date'] = date('Y-m-d');
							}
						}
                    }
                    if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding) {
                        $this->request->data['Project']['project_funding_start_date'] = date('Y-m-d');
                    }
					$this->request->data['Project']['ip_id'] = $this->Project->toSaveIp();
                    // validating ProjectReward data
                    $is_reward_valid = true;
                    if (Configure::read('Project.is_enable_project_rewards')) {
                        foreach($this->request->data['ProjectReward'] as $key => $projectReward) {
                            if (!empty($projectReward)) {
                                $data['ProjectReward']['max_amount'] = $this->request->data['Project']['needed_amount'];
                                $data['ProjectReward']['min_amount'] = !empty($this->request->data['Project']['min_amount_to_fund']) ? $this->request->data['Project']['min_amount_to_fund'] : '0';
                                $data['ProjectReward']['pledge_type_id'] = !empty($this->request->data['Project']['pledge_type_id']) ? $this->request->data['Project']['pledge_type_id'] : ConstPledgeTypes::Any;
                                $data['ProjectReward']['is_allow_over_funding'] = !empty($this->request->data['Project']['is_allow_over_funding']) ? $this->request->data['Project']['is_allow_over_funding'] : 0;
                                $data['ProjectReward']['pledge_amount'] = $projectReward['pledge_amount'];
                                $data['ProjectReward']['reward'] = $projectReward['reward'];
                                $data['ProjectReward']['pledge_max_user_limit'] = $projectReward['pledge_max_user_limit'];
                                $this->Project->ProjectReward->set($data);
                                if (!$this->Project->ProjectReward->validates()) {
                                    $projectRewardValidationError[$key] = $this->Project->ProjectReward->validationErrors;
                                    $is_reward_valid = false;
                                }								
                            }
                        }
                        unset($this->Project->ProjectReward->validationErrors);
                        if (!empty($projectRewardValidationError)) {
							$this->Project->ProjectReward->validationErrors = array();
                            foreach($projectRewardValidationError as $key => $error) {
                                $this->Project->ProjectReward->validationErrors[$key] = $error;
                            }
                        }
                    }
					if($this->request->data['UserProfile']['PaymentInfomation'] != ""){
	                    $paypal_account = 1;
	                    $this->Project->User->UserProfile->updateAll(array(
								'UserProfile.payment_infomation' => "'".$this->request->data['UserProfile']['PaymentInfomation']."'",
							) , array(
								'UserProfile.user_id' => $this->request->data['UserProfile']['id']
							));
					}else{
						$this->Project->set($this->request->data);
						$this->Project->User->UserProfile->set($this->request->data);
						$this->Project->User->UserProfile->validates();
	                    $paypal_account = 1;
	                    if (isset($this->request->data['UserProfile']['paypal_account'])) {
	                        $this->loadModel('Payment');
	                        $rsPayStatus = $this->Payment->getVerifiedStatus($this->request->data['UserProfile']);
	                        if (strtoupper($rsPayStatus['responseEnvelope.ack']) != 'SUCCESS' || strtoupper($rsPayStatus['accountStatus']) != 'VERIFIED') {
	                            $paypal_account = 0;
	                            $this->Project->User->UserProfile->validationErrors['paypal_account'] = __l('Enter verified PayPal email and the name associated with it');
	                        }						
	                    }
						//$this->Project->User->UserProfile->
					}
                    $this->Project->State->set($this->request->data);
                    $this->Project->City->set($this->request->data);
                    if ($this->Project->validates()& empty($this->Project->ProjectMedia->validationErrors) & $this->Project->Attachment->validates() & $this->Project->City->validates() & $this->Project->State->validates() && $is_reward_valid && $paypal_account) {
                        $this->Project->create();
                        if (Configure::read('Project.listing_fee')) {
                            $this->Project->Behaviors->detach('Logable');
                        }
						if (!empty($this->request->data['Project']['country_id'])) {
							$this->request->data['Project']['country_id'] = $this->Project->Country->findCountryId($this->request->data['Project']['country_id']);
						}
                        $this->request->data['State']['country_id'] = $this->request->data['Project']['country_id'];
                        $this->request->data['Project']['state_id'] = !empty($this->request->data['State']['id']) ? $this->request->data['State']['id'] : $this->Project->State->findOrSaveAndGetIdWithArray($this->request->data['State']['name'], $this->request->data['State']);
                        $this->request->data['City']['state_id'] = $this->request->data['Project']['state_id'];
                        $this->request->data['City']['country_id'] = $this->request->data['Project']['country_id'];
                        $this->request->data['Project']['city_id'] = !empty($this->request->data['City']['id']) ? $this->request->data['City']['id'] : $this->Project->City->findOrSaveAndGetIdWithArray($this->request->data['City']['name'], $this->request->data['City']);
                        if(empty($this->request->data['Project']['reserve_amount']))
                        {
                           $this->request->data['Project']['reserve_amount'] = 0;
                        }
                        if ($this->Project->save($this->request->data, false)) {

                            if (!empty($this->request->data['UserProfile']['paypal_account'])) {
                                if (empty($this->request->data['UserProfile']['id'])) {
                                    $this->request->data['UserProfile']['user_id'] = $this->request->data['Project']['user_id'];
                                }
                                $this->Project->User->UserProfile->save($this->request->data['UserProfile'], false);
                            }
                            
                            if (!empty($this->request->data['Attachment']['filename']['name'])) {
                                $this->Project->Attachment->create();
                                $this->request->data['Attachment']['class'] = 'Project';
                                $this->request->data['Attachment']['foreign_id'] = $this->Project->getLastInsertId();
                                $this->Project->Attachment->save($this->request->data['Attachment']);
                            }
                            if (Configure::read('Project.is_enable_project_rewards')) {
                                if (!empty($this->request->data['ProjectReward'])) {
                                    foreach($this->request->data['ProjectReward'] as $projectReward) {
                                        if ($projectReward['pledge_amount']) {
                                            $data['ProjectReward']['project_id'] = $this->Project->id;
                                            $data['ProjectReward']['pledge_amount'] = $projectReward['pledge_amount'];
                                            $data['ProjectReward']['reward'] = $projectReward['reward'];
                                            $data['ProjectReward']['pledge_max_user_limit'] = $projectReward['pledge_max_user_limit'];
                                            $this->Project->ProjectReward->create();
                                            $this->Project->ProjectReward->save($data);
                                        }
                                    }
                                }
                            }

							 if (!empty($this->request->data['ProjectMedia'])) {
                                 for($i = 0 ; $i < 5 ; $i++ ) {
                                 if ($this->request->data['ProjectMedia'][$i]['filename']['error'] == 1) {
                                    $attachmentValidationError[$i] = sprintf(__l('The file uploaded is too big, only files less than %s permitted') , ini_get('upload_max_filesize'));
                                    $is_form_valid = false;
                                    continue;
                                 }
								 
                                 if (!empty($this->request->data['ProjectMedia'][$i]['filename']['tmp_name'])) {
                                     $image_info = getimagesize($this->request->data['ProjectMedia'][$i]['filename']['tmp_name']);
                                     $this->request->data['ProjectMedia']['filename'] = $this->request->data['ProjectMedia'][$i]['filename'];
                                     $this->request->data['ProjectMedia']['filename']['type'] = $image_info['mime'];
                                     $this->Project->ProjectMedia->Behaviors->attach('ImageUpload', Configure::read('project.file'));
                                     $this->Project->ProjectMedia->set($this->request->data);
                                 if (!$this->Project->validates() |!$this->Project->ProjectMedia->validates()) {
                                     $attachmentValidationError[$i] = $this->Project->ProjectMedia->validationErrors;
                                     $is_form_valid = false;
                                     $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
                                    }
                                  }
								 $this->request->data['ProjectMedia'][$i]['class'] = 'ProjectMedia';
                                 $this->request->data['ProjectMedia'][$i]['foreign_id'] = $this->Project->getLastInsertId();
                                 $this->Project->Attachment->create();
                                 $this->Project->Attachment->save($this->request->data['ProjectMedia'][$i]);
                                  }
                                }

                                if (!empty($attachmentValidationError)) {
                                   foreach($attachmentValidationError as $key => $error) {
                                     $this->Project->ProjectMedia->validationErrors[$key]['filename'] = $error;
                                   }
                                }
                                $project = $this->Project->find('first', array(
                                'conditions' => array(
                                    'Project.id = ' => $this->Project->id
                                ) ,
                                'contain' => array(
                                    'Attachment' => array(
                                        'fields' => array(
                                            'Attachment.id',
                                            'Attachment.filename',
                                            'Attachment.dir',
                                            'Attachment.width',
                                            'Attachment.height'
                                        )
                                    ) ,
                                    'ProjectCategory',
                                    'User',
                                ) ,
                                'recursive' => 2
                            ));
                            if ((!Configure::read('Project.listing_fee')) and !Configure::read('Project.is_auto_approve') and $project['Project']['project_status_id'] == ConstProjectStatus::Pending  and !($project['Project']['admin_suspend'])) {
                                $this->Project->_sendAlertOnProjectAdd($project, 'New Project');
                            }
                            /*
                            After Adding projects, it is posted in Site Facebook and Site Twitter account
                            If user logged using Fb_connect or twitter account, it will be posted on their facebook and twitter account respectively
                            */
                            $url = Router::url(array(
                                'controller' => 'projects',
                                'action' => 'view',
                                $project['Project']['slug'],
                            ) , true);
                            // Post on user facebook
                            $user = $this->Project->User->UserPermissionPreference->find('first', array(
                                'conditions' => array(
                                    'UserPermissionPreference.user_id' => $project['Project']['user_id']
                                ) ,
                                'recursive' => - 1
                            ));
                            if (Configure::read('social_networking.post_project_on_user_facebook') && $user['UserPermissionPreference']['fb_status_new_project']) {
                                if ($project['User']['is_facebook_register']) {
                                    $fb_message = $project['User']['username'] . ' ' . __l('created a new project') . ' "' . $this->request->data['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                                    $getFBReturn = $this->postOnFacebook($project, $fb_message, 0);
                                }
                            }
							//pr(get_included_files());
							App::import('Core', 'ComponentCollection');
							$collection = new ComponentCollection();
							App::import('Component', 'OauthConsumer');
							$this->OauthConsumer = new OauthConsumerComponent($collection);
                            // post on user twitter
                            if (Configure::read('social_networking.post_project_on_user_twitter') && $user['UserPermissionPreference']['twitter_status_new_project']) {
                                if (!empty($project['User']['twitter_access_token']) && !empty($project['User']['twitter_access_key'])) {
                                    $message = $project['User']['username'] . ' ' . __l('created a new project') . ' "' . $this->request->data['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                                    $xml = $this->OauthConsumer->post('Twitter', $user['User']['twitter_access_token'], $user['User']['twitter_access_key'], 'https://twitter.com/statuses/update.xml', array(
                                        'status' => $message
                                    ));
                                }
                            }
                            // post on site facebook
                            if (Configure::read('Project.post_project_on_facebook') && $user['UserPermissionPreference']['fb_status_new_project']) {
                                $fb_message = $project['User']['username'] . ' ' . __l('created a new project') . ' "' . $this->request->data['Project']['name'] . '" in' . ' ' . Configure::read('site.name');
                                $getFBReturn = $this->postOnFacebook($project, $fb_message, 1);
                            }
                            // post on site twitter
                            if (Configure::read('Project.post_project_on_twitter') && $user['UserPermissionPreference']['twitter_status_new_project']) {
                                $message = 'via' . ' ' . '@' . Configure::read('twitter.username') . ': ' . $url . ' ' . $project['User']['username'] .' '. __l('created a new project') . ' "'.$this->request->data['Project']['name'].'"';
                                $xml = $this->OauthConsumer->post('Twitter', Configure::read('twitter.site_user_access_token') , Configure::read('twitter.site_user_access_key') , 'https://twitter.com/statuses/update.xml', array(
                                    'status' => $message
                                ));
                            }
                            if (Configure::read('Project.listing_fee') && $this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
                                $this->Session->setFlash(__l('Project has been added successfully and it will be list out after paying the listing fee') , 'default', null, 'success');
                                $this->redirect(array(
                                    'controller' => 'payments',
                                    'action' => 'project_pay_now',
                                    $this->Project->id
                                ));
                            } else {
                                if (($project['Project']['project_status_id'] == ConstProjectStatus::Pending || $project['Project']['admin_suspend']) && $this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
                                    if ($project['Project']['admin_suspend']) {
                                        $this->Session->setFlash(__l('Project has been suspended, due to some bad words.') , 'default', null, 'error');
                                    } else {
                                        $this->Session->setFlash(__l('Project has been added.  Admin will approve your project') , 'default', null, 'success');
                                    }
                                    $this->redirect(array(
                                        'controller' => 'users',
                                        'action' => 'dashboard',
                                        'admin' => false
                                    ));
                                } else {
                                    $this->Session->setFlash(__l('Project has been added.') , 'default', null, 'success');
                                    $this->redirect(array(
                                        'controller' => 'projects',
                                        'action' => 'view',
                                        $project['Project']['slug'],
                                        'admin' => false
                                    ));
                                }
                            }
                        }
                    } else {
                        $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
                    }
                }
            } else {
                $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
            }
        }
        if (empty($this->request->data['Project']['project_funding_end_date'])) {
            $date = strtotime(date('Y-m-d', strtotime(date('Y-m-d'))) . ' + ' . Configure::read('Project.paypal_expiry_date') . ' days');
            $this->request->data['Project']['project_funding_end_date'] = date('Y-m-d', $date);
        }
        if (!empty($userProfile)) {
            if (empty($this->request->data['Project']['country_id'])) {
                $this->request->data['Project']['country_id'] = !empty($userProfile['UserProfile']['country_id']) ? $userProfile['UserProfile']['country_id'] : '';
                $this->request->data['Country']['name'] = !empty($userProfile['UserProfile']['country_id']) ? $userProfile['Country']['name'] : '';
				$this->request->data['Country']['iso2'] = !empty($userProfile['Country']['iso2']) ? $userProfile['Country']['iso2'] : '';
            }
            if (empty($this->request->data['State']['name'])) {
                $this->request->data['State']['name'] = !empty($userProfile['UserProfile']['state_id']) ? $userProfile['State']['name'] : '';
            }
            if (empty($this->request->data['City']['name'])) {
                $this->request->data['City']['name'] = !empty($userProfile['UserProfile']['city_id']) ? $userProfile['City']['name'] : '';
            }
            $this->request->data['User']['name'] = !empty($userProfile['User']['username']) ? $userProfile['User']['username'] : $this->Auth->user('username');
        }
        if (empty($this->request->data['Project']['user_id']) && $this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            $this->request->data['Project']['user_id'] = $this->Auth->user('id');
        }
        $this->set('userProfile', $userProfile);
        $pledgeTypes = $this->Project->PledgeType->find('list', array(
            'conditions' => array(
                'PledgeType.is_active' => 1
            ) ,
        ));
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
            if (!Configure::read('Project.is_allow_user_to_set_minimum_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Minimum]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_suggested_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Reward]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_multiple_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Multiple]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_fixed_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Fixed]);
            }
        }
        $users = $this->Project->User->find('list', array(
            'conditions' => array(
                'User.is_active' => 1
            ) ,
			'order' => array(
                'User.username' => 'asc'
            ) ,
        ));
        $projectStatuses = $this->Project->ProjectStatus->find('list', array(
            'conditions' => array(
                'ProjectStatus.id' => array(
                    ConstProjectStatus::Pending,
                    ConstProjectStatus::OpenForFunding
                ) ,
            ) ,
        ));
		
		if(!empty($this->request->params['named']['name'])){
			$this->request->data['Project']['name'] = $this->request->params['named']['name'];
		}
        $projectCategories = $this->Project->ProjectCategory->find('list', array(
			 'order' => array(
                'ProjectCategory.name' => 'asc'
            ) ,
			));
        $this->loadModel('PaymentGateway');
		$paymentGateways = $this->PaymentGateway->find('all',array(
            'fields' => array(
                    'PaymentGateway.id',
        			'PaymentGateway.is_active',
			    ) ,
            'recursive' => -1
        ));
        $this->set('paymentGateways', $paymentGateways);
        $countries = $this->Project->Country->find('list', array('fields' => array('Country.iso2', 'Country.name')));
        $this->set(compact('users', 'projectStatuses', 'projectCategories', 'countries', 'pledgeTypes'));
        if ($step == 1) {
            $this->render('guidelines');
        }
    }
	public function flashupload()
    {
        $this->Project->Attachment->Behaviors->attach('ImageUpload', Configure::read('project.file'));
        $this->XAjax->flashupload();
    }
    // Posting Project on Facebook
    public function postOnFacebook($project = null, $message = null, $admin = null)
    {
        if (!empty($project)) {
            $slug = $project['Project']['slug'];
            $image_options = array(
                'dimension' => 'normal_thumb',
                'class' => '',
                'alt' => $project['Project']['name'],
                'title' => $project['Project']['name'],
                'type' => 'jpg'
            );
            if ($admin) {
                $facebook_dest_user_id = Configure::read('facebook.page_id') ? Configure::read('facebook.page_id') : Configure::read('facebook.fb_user_id');
                $facebook_dest_access_token = Configure::read('facebook.fb_access_token');
            } else {
                $facebook_dest_user_id = $project['User']['fb_user_id'];
                $facebook_dest_access_token = $project['User']['fb_access_token'];
            }
            App::import('Vendor', 'facebook/facebook');
            $this->facebook = new Facebook(array(
                'appId' => Configure::read('facebook.app_id') ,
                'secret' => Configure::read('facebook.fb_secrect_key') ,
                'cookie' => true
            ));
            if (empty($message)) {
                $message = $project['Project']['name'];
            }
            $image_url = Router::url('/', true) . $this->Project->getImageUrl('Project', $project['Attachment'], $image_options);
            $image_link = Router::url(array(
                'controller' => 'projects',
                'action' => 'view',
                'admin' => false,
                $slug
            ) , true);
            try {
                $getPostCheck = $this->facebook->api('/' . $facebook_dest_user_id . '/feed', 'POST', array(
                    'access_token' => $facebook_dest_access_token,
                    'message' => $message,
                    'picture' => $image_url,
                    'icon' => $image_url,
                    'link' => $image_link,
                    'description' => $project['Project']['description']
                ));
            }
            catch(Exception $e) {
                return 2;
            }
        }
    }
    public function edit($id = null)
    {
        $this->pageTitle = __l('Edit Project');
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id = ' => $id,
            ) ,
            'recursive' => - 1
        ));
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $id
            ) ,
            'fields' => array(
                'DATEDIFF(Project.project_funding_end_date,now()) as enddate',
                'Project.id',
                'Project.created',
                'Project.modified',
                'Project.name',
                'Project.description',
                'Project.short_description',
                'Project.user_id',
                'Project.project_category_id',
                'Project.project_status_id',
                'Project.needed_amount',
				'Project.reserve_amount',
				'Project.project_funding_start_date',
                'Project.project_funding_end_date',
                'Project.collected_amount',
                'Project.collected_percentage',
                'Project.total_ratings',
                'Project.project_rating_count',
                'Project.project_view_count',
                'Project.project_fund_count',
                'Project.project_comment_count',
                'Project.blog_count',
                'Project.slug',
                'Project.is_active',
                'Project.is_active',
                'Project.ip_id',
                'Project.is_recommended',
                'Project.is_allow_over_funding',
                'Project.video_embed_url',
                'Project.admin_suspend',
                'Project.is_system_flagged',
                'Project.detected_suspicious_words',
                'Project.project_follower_count',
                'Project.linkedin_url',
                'Project.facebook_url',
                'Project.twitter_url',
                'Project.youtube_url',
                'Project.myspace_url',
                'Project.website_url',
                'Project.imdb_url',
                'Project.pledge_type_id',
                'Project.feed_url',
                'Project.facebook_feed_url',
                'Project.twitter_feed_url',
                'Project.project_feed_count',
                'Project.actual_rating',
            ) ,
            'contain' => array(
			    'User' => array(
    			'fields' => array(
                'User.username',
	            )),
				'Country' => array(
                    'fields' => array(
                        'Country.name',
                        'Country.iso2'
                    )
                ) ,
                'City' => array(
                    'fields' => array(
                        'City.name',
                        'City.slug'
                    )
                ) ,
                'Attachment',
                'ProjectReward',
            ) ,
            'recuesive' => 2
        ));
        $this->set('project', $project);
		if(!($project['Project']['project_status_id'] == ConstProjectStatus::Pending) && !Configure::read('Project.is_allow_project_owner_to_edit_project_in_open_status')){
         throw new NotFoundException(__l('Invalid request')); 
		}
        if ((!($project['Project']['project_status_id'] == ConstProjectStatus::Pending  || $project['Project']['project_status_id'] == ConstProjectStatus::OpenForIdea || $project['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding) )  && ($this->Auth->user('user_type_id') != ConstUserTypes::Admin)) {
            $this->Session->setFlash(__l('Project has been closed or expired.') , 'default', null, 'error');
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'view',
                $project['Project']['slug']
            ));
        }
        if (!empty($this->request->data)) {
            if (!empty($this->request->data['ProjectMedia'])) {
                                 for($i = 0 ; $i < 5 ; $i++ ) {
                                 if ($this->request->data['ProjectMedia'][$i]['filename']['error'] == 1) {
                                    $attachmentValidationError[$i] = sprintf(__l('The file uploaded is too big, only files less than %s permitted') , ini_get('upload_max_filesize'));
                                    $is_form_valid = false;
                                    continue;
                                 }
                                 if (!empty($this->request->data['ProjectMedia'][$i]['filename']['tmp_name'])) {
                                     $image_info = getimagesize($this->request->data['ProjectMedia'][$i]['filename']['tmp_name']);
                                     $this->request->data['ProjectMedia']['filename'] = $this->request->data['ProjectMedia'][$i]['filename'];
                                     $this->request->data['ProjectMedia']['filename']['type'] = $image_info['mime'];
                                     $this->Project->ProjectMedia->Behaviors->attach('ImageUpload', Configure::read('project.file'));
                                     $this->Project->ProjectMedia->set($this->request->data);
                                     if (!$this->Project->validates() |!$this->Project->ProjectMedia->validates()) {
                                     $attachmentValidationError[$i] = $this->Project->ProjectMedia->validationErrors;
                                     $is_form_valid = false;
                                     $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
                                    }
                                  }
								 
                                  }
                                }

                                if (!empty($attachmentValidationError)) {
                                   foreach($attachmentValidationError as $key => $error) {
                                     $this->Project->ProjectMedia->validationErrors[$key]['filename'] = $error;
                                   }
                                }
            if (!empty($this->request->data['Attachment']['filename']['name'])) {
		        $this->Project->Attachment->Behaviors->attach('ImageUpload', Configure::read('Project.image'));
                $this->request->data['Attachment']['filename']['type'] = get_mime($this->request->data['Attachment']['filename']['tmp_name']);
                $this->Project->Attachment->set($this->request->data);
            }
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::FundingClosed) {
                if ($project['Project']['project_funding_end_date'] < $this->request->data['Project']['project_funding_end_date']) {
                    $this->request->data['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
                }
            }
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding) {
                $this->request->data['Project']['project_funding_start_date'] = date('Y-m-d');
            }
            $is_reward_valid = true;
            if (!empty($this->request->data['Project']['pledge_type_id']) && $this->request->data['Project']['pledge_type_id'] == ConstPledgeTypes::Any) {
                unset($this->request->data['Project']['min_amount_to_fund']);
            }
			//to delete the existing data from project reward table 
			 $this->Project->ProjectReward->deleteAll(array(
                        'ProjectReward.project_id' => $this->request->data['Project']['id']
                    ));
            if (Configure::read('Project.is_enable_project_rewards') && !empty($this->request->data['ProjectReward'])) {
                foreach($this->request->data['ProjectReward'] as $key => $projectReward) {
                    if (!empty($projectReward)) {
                        $data['ProjectReward']['max_amount'] = round($this->request->data['Project']['needed_amount']);
                        $data['ProjectReward']['min_amount'] = !empty($this->request->data['Project']['min_amount_to_fund']) ? round($this->request->data['Project']['min_amount_to_fund']) : '0';
                        $data['ProjectReward']['pledge_type_id'] = !empty($this->request->data['Project']['pledge_type_id']) ? $this->request->data['Project']['pledge_type_id'] : ConstPledgeTypes::Any;
                        $data['ProjectReward']['allow_over_funding'] = !empty($this->request->data['Project']['allow_over_funding']) ? $this->request->data['Project']['allow_over_funding'] : 0;
                        $data['ProjectReward']['pledge_amount'] = $projectReward['pledge_amount'];
                        $data['ProjectReward']['reward'] = $projectReward['reward'];
                        $data['ProjectReward']['pledge_max_user_limit'] = $projectReward['pledge_max_user_limit'];
                        $this->Project->ProjectReward->set($data);
                        if (!$this->Project->ProjectReward->validates()) {
                            $projectRewardValidationError[$key] = $this->Project->ProjectReward->validationErrors;
                            $is_reward_valid = false;
                        }
                    }
                }
	
                unset($this->Project->ProjectReward->validationErrors);
                 if (!empty($projectRewardValidationError)) {
							$this->Project->ProjectReward->validationErrors = array();
                            foreach($projectRewardValidationError as $key => $error) {
                                $this->Project->ProjectReward->validationErrors[$key] = $error;
                            }
                        }
            }
            $this->Project->State->set($this->request->data);
            $this->Project->City->set($this->request->data);
            $this->Project->set($this->request->data);
            if ($this->Project->validates() & empty($this->Project->ProjectMedia->validationErrors) & $this->Project->Attachment->validates() & $this->Project->City->validates() & $this->Project->State->validates() && $is_reward_valid) {
				if (!empty($this->request->data['Project']['country_id'])) {
					$this->request->data['Project']['country_id'] = $this->Project->Country->findCountryId($this->request->data['Project']['country_id']);
				}
				if (!empty($this->request->data['ProjectMedia'])) {
                                 for($i = 0 ; $i < 5 ; $i++ ) {
                                 if ($this->request->data['ProjectMedia'][$i]['filename']['error'] == 1) {
                                    $attachmentValidationError[$i] = sprintf(__l('The file uploaded is too big, only files less than %s permitted') , ini_get('upload_max_filesize'));
                                    $is_form_valid = false;
                                    continue;
                                 }
                                 if (!empty($this->request->data['ProjectMedia'][$i]['filename']['tmp_name'])) {
                                     $image_info = getimagesize($this->request->data['ProjectMedia'][$i]['filename']['tmp_name']);
                                     $this->request->data['ProjectMedia']['filename'] = $this->request->data['ProjectMedia'][$i]['filename'];
                                     $this->request->data['ProjectMedia']['filename']['type'] = $image_info['mime'];
                                     $this->Project->ProjectMedia->Behaviors->attach('ImageUpload', Configure::read('project.file'));
                                     $this->Project->ProjectMedia->set($this->request->data);
                                 if (!$this->Project->validates() |!$this->Project->ProjectMedia->validates()) {
                                     $attachmentValidationError[$i] = $this->Project->ProjectMedia->validationErrors;
                                     $is_form_valid = false;
                                     $this->Session->setFlash(__l('Project could not be added. Please, try again.') , 'default', null, 'error');
                                    }
                                  }
								 $this->request->data['ProjectMedia'][$i]['class'] = 'ProjectMedia';
                                 $this->request->data['ProjectMedia'][$i]['foreign_id'] = $this->request->data['Project']['id'];
                                 $this->Project->Attachment->create();
                                 $this->Project->Attachment->save($this->request->data['ProjectMedia'][$i]);
                                  }
                                }
                $this->request->data['State']['country_id'] = $this->request->data['Project']['country_id'];
                $this->request->data['Project']['state_id'] = !empty($this->request->data['State']['id']) ? $this->request->data['State']['id'] : $this->Project->State->findOrSaveAndGetIdWithArray($this->request->data['State']['name'], $this->request->data['State']);
                $this->request->data['City']['state_id'] = $this->request->data['Project']['state_id'];
                $this->request->data['City']['country_id'] = $this->request->data['Project']['country_id'];
                $this->request->data['Project']['city_id'] = !empty($this->request->data['City']['id']) ? $this->request->data['City']['id'] : $this->Project->City->findOrSaveAndGetIdWithArray($this->request->data['City']['name'], $this->request->data['City']);
                if(empty($this->request->data['Project']['reserve_amount']))
                        {
                           $this->request->data['Project']['reserve_amount'] = 0;
                        }
                if ($this->Project->save($this->request->data,false)) {
                    if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::FundingClosed) {
                        $this->Project->_executepay($this->request->data['Project']['id']);
                    } elseif ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::ProjectCancelled) {
                        $this->Project->_refund($this->request->data['Project']['id']);
                    }
                    if (!empty($this->request->data['Attachment']['filename']['name'])) {
                        $attach = $this->Project->Attachment->find('first', array(
                            'conditions' => array(
                                'Attachment.foreign_id' => $this->request->data['Project']['id'],
                                'Attachment.class' => 'Project'
                            ) ,
                            'fields' => array(
                                'Attachment.id'
                            ) ,
                            'recursive' => - 1
                        ));
                        $this->request->data['Attachment']['class'] = 'Project';
                        $this->request->data['Attachment']['foreign_id'] = $this->request->data['Project']['id'];
                        $this->request->data['Attachment']['id'] = $attach['Attachment']['id'];
                        $this->Project->Attachment->save($this->request->data['Attachment']);
                    }
					 
					if (!empty($this->request->data['ProjectReward'])) {
						foreach($this->request->data['ProjectReward'] as $projectReward) {
							if (!empty($projectReward['pledge_amount'])) {
								$data['ProjectReward']['project_id'] = $this->request->data['Project']['id'];
								$data['ProjectReward']['pledge_amount'] = $projectReward['pledge_amount'];
								$data['ProjectReward']['reward'] = $projectReward['reward'];
								$data['ProjectReward']['pledge_max_user_limit'] = $projectReward['pledge_max_user_limit'];
								if (!empty($projectReward['id'])) {
									$data['ProjectReward']['id'] = $projectReward['id'];
								} else {
									$this->Project->ProjectReward->create();
									$this->Project->ProjectReward->set($data);
								}
								$this->Project->ProjectReward->save($data, false);
								unset($data);
							}
						}
					}
                    $this->Session->setFlash(__l('Project has been updated') , 'default', null, 'success');
                    if ($project['Project']['name'] != $this->request->data['Project']['name']) {
                        $project = $this->Project->find('first', array(
                            'conditions' => array(
                                'Project.id' => $this->request->data['Project']['id']
                            ) ,
                            'fields' => array(
                                'Project.slug',
                            ) ,
                            'recuesive' => - 1
                        ));
                    }
                    if (!empty($this->request->params['admin'])) {
                        $this->redirect(array(
                            'controller' => 'projects',
                            'action' => 'index',
                            'admin' => true,
                        ));
                    } else {
                        $this->redirect(array(
                            'controller' => 'projects',
                            'action' => 'view',
                            $project['Project']['slug'],
                            'admin' => false,
                        ));
                    }
                } else {
					$this->request->data['Attachment'] = $project['Attachment'];
					if (empty($this->request->data['ProjectReward']) && !empty($project['ProjectReward'])) {
						$this->request->data['ProjectReward'] = $project['ProjectReward'];
					}
					$this->Session->setFlash(__l('Project could not be updated. Please, try again.') , 'default', null, 'error');
				}
            } else {
				$this->request->data['Attachment'] = $project['Attachment'];
				if (empty($this->request->data['ProjectReward']) && !empty($project['ProjectReward'])) {
					$this->request->data['ProjectReward'] = $project['ProjectReward'];
				}
                $this->Session->setFlash(__l('Project could not be updated. Please, try again.') , 'default', null, 'error');
            }
        } else {
            $this->request->data = $this->Project->read(null, $id);
            if (empty($this->request->data)) {
                throw new NotFoundException(__l('Invalid request'));
            }
			$this->request->data['Project']['country_id'] = $this->request->data['Country']['iso2'];
        }
        if ($this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::Pending) {
                $condition['ProjectStatus.id'] = array(
                    ConstProjectStatus::Pending,
                    ConstProjectStatus::OpenForFunding,
                    ConstProjectStatus::ProjectCancelled
                );
            }
	            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::OpenForIdea) {
                $condition['ProjectStatus.id'] = array(
					ConstProjectStatus::OpenForIdea,
                    ConstProjectStatus::OpenForFunding,
                    ConstProjectStatus::ProjectCancelled
                );
            }
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding) {
                $condition['ProjectStatus.id'] = array(
                    ConstProjectStatus::OpenForFunding,
                    ConstProjectStatus::FundingClosed,
                    ConstProjectStatus::ProjectCancelled,
                );
            }
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::FundingClosed) {
                $condition['ProjectStatus.id'] = array(
                    ConstProjectStatus::FundingClosed,
                    ConstProjectStatus::OpenForFunding,
                    ConstProjectStatus::FundingExpired,
                );
            }
            if ($this->request->data['Project']['project_status_id'] == ConstProjectStatus::ProjectCancelled) {
                $condition['ProjectStatus.id'] = array(
                    ConstProjectStatus::ProjectCancelled,
                    ConstProjectStatus::OpenForFunding
                );
            }
            if (empty($condition)) {
                $condition['ProjectStatus.id'] = $this->request->data['Project']['project_status_id'];
            }
            $projectStatuses = $this->Project->ProjectStatus->find('list', array(
                'conditions' => array(
                    'ProjectStatus.is_active' => 1,
                    $condition
                )
            ));
            $users = $this->Project->User->find('list');
            $this->set(compact('users', 'projectStatuses'));
        }
        $pledgeTypes = $this->Project->PledgeType->find('list', array(
            'conditions' => array(
                'PledgeType.is_active' => 1
            ) ,
        ));
        if ($this->Auth->user('user_type_id') != ConstUserTypes::Admin) {
            if (!Configure::read('Project.is_allow_user_to_set_minimum_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Minimum]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_suggested_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Reward]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_multiple_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Multiple]);
            }
            if (!Configure::read('Project.is_allow_user_to_set_fixed_amount_pledge')) {
                unset($pledgeTypes[ConstPledgeTypes::Fixed]);
            }
        }
        $projectCategories = $this->Project->ProjectCategory->find('list');
        $countries = $this->Project->Country->find('list', array('fields' => array('Country.iso2', 'Country.name')));
        if(!empty($project['Project']['name'])){
			$this->pageTitle .= __l(' - '.$project['Project']['name']);
		}
        $this->set(compact('projectCategories', 'countries', 'pledgeTypes'));
    }
    public function admin_cancel($id = null)
    {
        $this->setAction('cancel', $id);
    }
    public function cancel($id = null)
    {
        $this->pageTitle = __l('Cancel Project');
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $id
            ) ,
            'contain' => array(
                'User' => array(
                    'fields' => array(
                        'User.id',
                        'User.username',
                        'User.email'
                    ) ,
                ) ,
                'ProjectFund' => array(
                    'fields' => array(
                        'ProjectFund.user_id'
                    )
                ) ,
                'ProjectFollower' => array(
                    'fields' => array(
                        'ProjectFollower.user_id'
                    )
                ) ,
            ) ,
            'recursive' => 2
        ));
        if (empty($project) || (!empty($project) && ((!Configure::read('Project.is_allow_owner_project_cancel') && $this->Auth->user('id') == $project['Project']['user_id']) || $this->Auth->user('id') != $project['Project']['user_id'] && $this->Auth->user('user_type_id') != ConstUserTypes::Admin))) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Project->_refund($id);
        $this->request->data['Project']['id'] = $id;
        $this->request->data['Project']['project_status_id'] = ConstProjectStatus::ProjectCancelled;
        $this->request->data['Project']['project_cancelled_date'] = date('Y-m-d H:i:s');
		$this->request->data['Project']['is_active'] = 0;
        if ($this->Project->save($this->request->data, false)) {
            // Project cancelled notify Mail process
            // sending Mail to owner
            $owner_user[] = $project['Project']['user_id'];
            $return_owner_lists = $this->Project->_sendAlertOnProjectCancelled(array_unique($owner_user) , $project, ConstProjectUsers::Owner);
            // send mail to backed
            $pledged_users = Set::extract('/ProjectFund/user_id', $project);
            $pledged_user_lists = $this->Project->_sendAlertOnProjectCancelled(array_unique($pledged_users) , $project, ConstProjectUsers::Backer, $return_owner_lists);
            // send mail to followers
            $follow_users = Set::extract('/ProjectFollower/user_id', $project);
            $this->Project->_sendAlertOnProjectCancelled(array_unique($follow_users) , $project, ConstProjectUsers::Follower, $pledged_user_lists);
            // Send mail to admin
            $this->Project->_sendAlertOnProjectStatusToAdmin($project, $project['Project']['project_status_id'], ConstProjectStatus::ProjectCancelled);
            $this->Session->setFlash(__l('Project has been canceled successfully') , 'default', null, 'success');
        } else {
            $this->Session->setFlash(__l('Project could not be cancelled') , 'default', null, 'error');
        }
        if ($this->Auth->user('user_type_id') == ConstUserTypes::Admin) {
            $this->redirect(array(
                'controller' => 'projects',
                'action' => 'index',
            ));
        } else {
            $this->redirect(array(
                'controller' => 'users',
                'action' => 'dashboard',
            ));
        }
    }
    public function admin_index()
    {
		unset($this->Project->validate['project_status_id']);
        $this->_redirectGET2Named(array(
            'project_status_id',
            'filter_id',
            'q'
        ));
        $this->pageTitle = __l('Projects');
        $conditions = array();
        // check the filer passed through named parameter
        if (isset($this->request->params['named']['filter_id'])) {
            $this->request->data['Project']['filter_id'] = $this->request->params['named']['filter_id'];
        }
        if (!empty($this->request->data['Project']['filter_id'])) {
            if ($this->request->data['Project']['filter_id'] == ConstMoreAction::Suspend) {
                $conditions['Project.admin_suspend'] = 1;
                $this->pageTitle.= __l(' - Suspended ');
            } elseif ($this->request->data['Project']['filter_id'] == ConstMoreAction::Active) {
                $conditions['Project.is_active'] = 1;
                $conditions['Project.admin_suspend'] = 0;
                $this->pageTitle.= __l(' - Active ');
            } elseif ($this->request->data['Project']['filter_id'] == ConstMoreAction::Inactive) {
                $conditions['Project.is_active'] = 0;
                $this->pageTitle.= __l(' - Inactive ');
            } elseif ($this->request->data['Project']['filter_id'] == ConstMoreAction::Flagged) {
                $conditions['Project.is_system_flagged'] = 1;
                $this->pageTitle.= __l(' - Flagged ');
            }
            $this->request->params['named']['filter_id'] = $this->request->data['Project']['filter_id'];
        }
        if (!empty($this->request->data['Project']['project_status_id'])) {
            $this->request->params['named']['project_status_id'] = $this->request->data['Project']['project_status_id'];
            $conditions['Project.project_status_id'] = $this->request->data['Project']['project_status_id'];
        } elseif (!empty($this->request->params['named']['project_status_id'])) {
            $this->request->data['Project']['project_status_id'] = $this->request->params['named']['project_status_id'];
            $conditions['Project.project_status_id'] = $this->request->data['Project']['project_status_id'];
        }elseif (!empty($this->request->params['named']['is_allow_over_funding'])) {
            $this->request->data['Project']['is_allow_over_funding'] = $this->request->params['named']['is_allow_over_funding'];
            $conditions['Project.is_allow_over_funding'] = $this->request->data['Project']['is_allow_over_funding'];
        }
		elseif (!empty($this->request->params['named']['transaction_type_id'])) {
            $this->request->data['Project']['transaction_type_id'] = $this->request->params['named']['transaction_type_id'];

			$foreigns = $this->Project->Transaction->find('list',
			                 array('conditions' =>
							           array('Transaction.class = ' => 'Project','Transaction.transaction_type_id = ' => ConstTransactionTypes::Project,),
									'fields' => array('Transaction.foreign_id ')
								  ));
			$conditions['Project.id'] = $foreigns;
        }
        if (!empty($this->request->data['Project']['project_status_id']) or !empty($this->request->data['Project']['project_status_id'])) {
            switch ($conditions['Project.project_status_id']) {
            case ConstProjectStatus::Pending:
                $this->pageTitle.= __l(' - Pending');
                break;

            case ConstProjectStatus::OpenForFunding:
                $this->pageTitle.= __l(' - Open For Funding');
                break;
			case ConstProjectStatus::OpenForIdea:
                $this->pageTitle.= __l(' - Open For Voting');
                break;

            case ConstProjectStatus::FundingClosed:
                $this->pageTitle.= __l('- Funding Closed');
                break;

            case ConstProjectStatus::FundingExpired:
                $this->pageTitle.= __l(' - Funding Expired');
                break;

            case ConstProjectStatus::ProjectCancelled:
                $this->pageTitle.= __l(' - Cancelled');
                break;

            case ConstProjectStatus::ReserveAmountReached:
                $this->pageTitle.= __l(' - Reserve Amount Reached');
                break;

            case ConstProjectStatus::GoalReached:
                $this->pageTitle.= __l(' - Goal Reached');
                break;

            default:
                break;
            }
        }
        if (isset($this->request->params['named']['q'])) {
            $conditions['AND']['OR'][]['Project.name LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $conditions['AND']['OR'][]['User.username LIKE'] = '%' . $this->request->params['named']['q'] . '%';
            $this->pageTitle.= sprintf(__l(' - Search - %s') , $this->request->params['named']['q']);
			$this->request->data['Project']['q'] = $this->request->params['named']['q'];
        }
        if (!empty($this->request->params['named']['type']) && $this->request->params['named']['type'] == 'listing_fee') {
            $conditions['Project.fee_amount !='] = '0.00';
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'day') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Project.created) <= '] = 0;
            $this->pageTitle.= __l(' - Added today');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'week') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Project.created) <= '] = 7;
            $this->pageTitle.= __l(' - Added in this week');
        }
        if (isset($this->request->params['named']['stat']) && $this->request->params['named']['stat'] == 'month') {
            $conditions['TO_DAYS(NOW()) - TO_DAYS(Project.created) <= '] = 30;
            $this->pageTitle.= __l(' - Added in this month');
        }
        if (!empty($this->request->params['named']['project_flag_category_id'])) {
            $project_flag = $this->Project->ProjectFlag->find('list', array(
                'conditions' => array(
                    'ProjectFlag.project_flag_category_id' => $this->request->params['named']['project_flag_category_id']
                ) ,
                'fields' => array(
                    'ProjectFlag.id',
                    'ProjectFlag.project_id'
                ) ,
                'recursive' => - 1
            ));
            $conditions['Project.id'] = $project_flag;
        }
        if (!empty($this->request->params['named']['project_category_id'])) {
            $conditions['Project.project_category_id'] = $this->request->params['named']['project_category_id'];
            $user = $this->{$this->modelClass}->ProjectCategory->find('first', array(
                'conditions' => array(
                    'ProjectCategory.id' => $this->request->params['named']['project_category_id']
                ) ,
                'fields' => array(
                    'ProjectCategory.id',
                    'ProjectCategory.name'
                ) ,
                'recursive' => - 1
            ));
            if (empty($user)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $this->pageTitle.= sprintf(__l(' - %s') , $user['ProjectCategory']['name']);
        } else if (!empty($this->request->params['named']['user_id'])) {
            $user = $this->{$this->modelClass}->User->find('first', array(
                'conditions' => array(
                    'User.id' => $this->request->params['named']['user_id']
                ) ,
                'fields' => array(
                    'User.id',
                    'User.username'
                ) ,
                'recursive' => - 1
            ));
            if (empty($user)) {
                throw new NotFoundException(__l('Invalid request'));
            }
            $conditions['Project.user_id'] = $this->request->params['named']['user_id'];
            $this->pageTitle.= sprintf(__l(' - %s') , $user['User']['username']);
        }
        $this->paginate = array(
            'conditions' => $conditions,
			'contain'=>array(
				'User',
				'ProjectStatus',
				'Attachment',
				'Ip' => array(
                    'City' => array(
                        'fields' => array(
                            'City.name',
                        )
                    ) ,
                    'State' => array(
                        'fields' => array(
                            'State.name',
                        )
                    ) ,
                    'Country' => array(
                        'fields' => array(
                            'Country.name',
                            'Country.iso2',
                        )
                    ) ,
                    'fields' => array(
                        'Ip.ip',
                        'Ip.latitude',
                        'Ip.longitude',
						'Ip.host'
                    )
                ) ,
			),
            'order' => array(
                'Project.id' => 'desc'
            ) ,
            'recursive' => 3
        );
        /// Status Based on Count
        $this->set('opened_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForFunding,
            )
        )));
		 $this->set('idea_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForIdea,
            )
        )));
        $this->set('pending_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::Pending,
            )
        )));
        $this->set('canceled_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::ProjectCancelled,
            )
        )));


		$this->set('allow_overfunding', $this->Project->find('count', array(
            'conditions' => array(
                'Project.is_allow_over_funding = ' => 1,
            )
        )));
		$this->set('goal_reached', $this->Project->find('count', array(
            'conditions' => array(
                'ProjectStatus.id = ' => ConstProjectStatus::GoalReached,
            )
        )));
		$this->set('reserve_amount_reached', $this->Project->find('count', array(
            'conditions' => array(
                'ProjectStatus.id = ' => ConstProjectStatus::ReserveAmountReached,
            )
        )));


        $this->set('closed_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::FundingClosed,
            )
        )));
		$this->set('open_for_idea', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForIdea,
            )
        )));

        $this->set('expired_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::FundingExpired,
            )
        )));

		 $this->set('paid_projects', $this->Project->Transaction->find('count', array(
            'conditions' => array(
                'Transaction.class = ' => 'Project',
                'Transaction.transaction_type_id = ' => ConstTransactionTypes::Project,
            )
        )));


        // total openid users list
        $this->set('suspended', $this->Project->find('count', array(
            'conditions' => array(
                'Project.admin_suspend = ' => 1,
            )
        )));
        $this->set('system_flagged', $this->Project->find('count', array(
            'conditions' => array(
                'Project.is_system_flagged = ' => 1,
            )
        )));
        $this->set('total_projects', $this->Project->find('count'));
        $this->set('projects', $this->paginate());
        $filters = $this->Project->isFilterOptions;
        $moreActions = $this->Project->moreActions;
        $projectStatuses = $this->Project->ProjectStatus->find('list', array(
            'conditions' => array(
                'ProjectStatus.is_active' => 1
            )
        ));
        $this->set(compact('moreActions', 'projectStatuses', 'filters'));
    }
    public function admin_view($slug = null)
    {
        $this->setAction('view', $slug);
    }
    public function admin_add()
    {
        $this->setAction('add');
    }
    public function admin_edit($id = null)
    {
        $this->setAction('edit', $id);
    }
    public function admin_capture_fund($project_id)
    {
        if (is_null($project_id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        //Get the project status
        $projectStatus = $this->Project->find('first', array(
            'conditions' => array(
                'Project.id' => $project_id
            ) ,
            'fields' => array(
                'Project.project_status_id',
                'Project.id',
            ) ,
            'recursive' => - 1,
        ));
        if ($projectStatus['Project']['project_status_id'] == ConstProjectStatus::OpenForFunding) {
            $this->Project->_executepay($projectStatus['Project']['id']);
            $this->Session->setFlash(__l('Funds are executed manually for all funded users') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_open_funding($id = null)
    {
		if (is_null($id)) {
			throw new NotFoundException(__l('Invalid request'));
		}
		if (!empty($this->request->params['named']['type'])) {
            $data = array();
            $data['Project']['project_status_id'] = ConstProjectStatus::OpenForIdea;
            $data['Project']['id'] = $id;
            $this->Project->save($data);
		   $this->Session->setFlash(__l('Idea has been opened for voting.') , 'default', null, 'success');
		} else {
            $data = array();
            $data['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
            $data['Project']['project_funding_start_date'] = date('Y-m-d');
            $data['Project']['id'] = $id;
            $this->Project->save($data);
        	$this->Session->setFlash(__l('Project has been opened for funding.') , 'default', null, 'success');
		}
        $this->redirect(array(
            'action' => 'index'
        ));
    }
    public function admin_delete($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Project->_refund($id);
        if ($this->Project->delete($id)) {
            $this->Session->setFlash(__l('Project deleted') , 'default', null, 'success');
            $this->redirect(array(
                'action' => 'index'
            ));
        } else {
            throw new NotFoundException(__l('Invalid request'));
        }
    }
    public function admin_update()
    {
        if (!empty($this->request->data['Project'])) {
            $this->Project->Behaviors->detach('SuspiciousWordsDetector');
            $this->Project->Behaviors->detach('Logable');
            $r = $this->request->data[$this->modelClass]['r'];
            $actionid = $this->request->data[$this->modelClass]['more_action_id'];
            unset($this->request->data[$this->modelClass]['r']);
            unset($this->request->data[$this->modelClass]['more_action_id']);
            $userIds = array();
            foreach($this->request->data['Project'] as $project_id => $is_checked) {
                if ($is_checked['id']) {
                    $projectIds[] = $project_id;
                }
            }
            if ($actionid && !empty($projectIds)) {
                if ($actionid == ConstMoreAction::Inactive) {
                    foreach($projectIds as $val) {
                        $project['Project']['is_active'] = 0;
                        $project['Project']['id'] = $val;
                        $this->Project->save($project, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been inactivated') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Active) {
                    foreach($projectIds as $val) {
                        $project['Project']['is_active'] = 1;
                        $project['Project']['id'] = $val;
                        $this->Project->save($project, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been activated') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Delete) {
                    foreach($projectIds as $id) {
                        $this->Project->_refund($id);
                        $this->Project->delete($id, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been deleted') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Approved) {
                    foreach($projectIds as $id) {
                        $this->Project->_refund($id);
                        $project['Project']['project_status_id'] = ConstProjectStatus::OpenForFunding;
						$project['Project']['project_funding_start_date'] = date('Y-m-d');
                        $project['Project']['id'] = $id;
                        $this->Project->save($project, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been opened') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Suspend) {
                    foreach($projectIds as $id) {
                        $this->Project->_refund($id);
                        $project['Project']['admin_suspend'] = 1;
                        $project['Project']['id'] = $id;
                        $this->Project->save($project, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been Suspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unsuspend) {
                    foreach($projectIds as $val) {
                        $project['Project']['admin_suspend'] = 0;
                        $project['Project']['id'] = $val;
                        $this->Project->save($project, false);
                    }
                    $this->Session->setFlash(__l('Checked projects has been Unsuspended') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Flagged) {
                    $this->Project->updateAll(array(
                        'Project.is_system_flagged' => 1
                    ) , array(
                        'Project.id' => $projectIds
                    ));
                    $this->Session->setFlash(__l('Checked projects has been Flagged') , 'default', null, 'success');
                } else if ($actionid == ConstMoreAction::Unflagged) {
                    $this->Project->updateAll(array(
                        'Project.is_system_flagged' => 0
                    ) , array(
                        'Project.id' => $projectIds
                    ));
                    $this->Session->setFlash(__l('Checked projects has been Unflagged') , 'default', null, 'success');
                }
            }
        }
        $this->redirect(Router::url('/', true) . $r);
    }
    public function admin_refund($project_id = null)
    {
        if (is_null($project_id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Project->Behaviors->detach('Logable');
        $this->Project->_refund($project_id);
        if (!empty($project)) {
            $this->Project->updateAll(array(
                'Project.project_status_id' => ConstProjectStatus::ProjectCancelled,
            ) , array(
                'Project.id' => $project_id
            ));
        }
        $this->redirect(array(
            'action' => 'index'
        ));
    }
    public function admin_update_status()
    {
        App::import('Core', 'ComponentCollection');
		$collection = new ComponentCollection();
		App::import('Component', 'Cron');
		$this->Cron = new CronComponent($collection);
        $this->Cron->update_project();
        $this->redirect(Router::url('/', true) . $_GET['f']);
    }
    public function admin_update_stats($id = null)
    {
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $this->Project->Behaviors->detach('Logable');
        if (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'active')) {
            $this->Project->updateAll(array(
                'Project.is_system_flagged' => 1
            ) , array(
                'Project.id' => $id
            ));
            $this->Session->setFlash(__l('Project has been flagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'deactivate')) {
            $this->Project->updateAll(array(
                'Project.is_system_flagged' => 0
            ) , array(
                'Project.id' => $id
            ));
            $this->Session->setFlash(__l('Project has been Unflagged') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'suspend')) {
            // refund amount
            $this->Project->_refund($id);            
			$this->Project->updateAll(array(
                'Project.admin_suspend' => 1
            ) , array(
                'Project.id' => $id
            ));
            $this->Session->setFlash(__l('Project has been suspend') , 'default', null, 'success');
        } elseif (!empty($this->request->params['named']['flag']) && ($this->request->params['named']['flag'] == 'unsuspend')) {            
			$this->Project->updateAll(array(
                'Project.admin_suspend' => 0
            ) , array(
                'Project.id' => $id
            ));
            $this->Session->setFlash(__l('Project has been unsuspend') , 'default', null, 'success');
        }
        $this->redirect(array(
            'action' => 'index',
        ));
    }
    public function guidelines()
    {
        $this->pageTitle = __l('Project - Guidelines');
		if (!empty($this->request->data)) {
            $this->Project->set($this->request->data);
            if ($this->Project->validates()) {
                $this->redirect(array(
                    'action' => 'add',
                ));
            }
        }
    }
	public function delete_attachment($project_id = null, $id = null)
    {   
        if (is_null($id)) {
            throw new NotFoundException(__l('Invalid request'));
        }

            if ($this->Project->Attachment->delete($id)) {
			
                $this->Session->setFlash(__l('Attachment has been deleted') , 'default', null, 'success');
                $this->redirect(array(
                    'controller' => 'projects',
                    'action' => 'edit',
                    $project_id
                ));
            } else {
                throw new NotFoundException(__l('Invalid request'));
            }
      
    }

    public function mediadownload($slug = null, $attachment_id = null)
    {
        //checking Authontication
        if (empty($slug) or empty($attachment_id)) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $project = $this->Project->find('first', array(
            'conditions' => array(
                'Project.slug =' => $slug,
            ) ,
            'contain' => array('ProjectMedia' => array('conditions' => array('ProjectMedia.id' => $attachment_id))),
            'recursive' => 1
        ));
        if (empty($project['ProjectMedia'][0])) {
            throw new NotFoundException(__l('Invalid request'));
        }
        $mime_type = $project['ProjectMedia'][0]['mimetype'];
        $filename = substr($project['ProjectMedia'][0]['filename'], 0, strrpos($project['ProjectMedia'][0]['filename'], '.'));
        $file_extension = substr($project['ProjectMedia'][0]['filename'], strrpos($project['ProjectMedia'][0]['filename'], '.') +1, strlen($project['ProjectMedia'][0]['filename']));
        $file_path = str_replace('\\', '/', 'media' . DS . $project['ProjectMedia'][0]['dir'] . DS . $project['ProjectMedia'][0]['filename']);
        // Code to download
        Configure::write('debug', 0);
        $this->view = 'Media';
        $this->autoLayout = false;
        $this->set('name', trim($filename));
        $this->set('download', true);
        $this->set('extension', trim($file_extension));
        $this->set('mimeType', trim($mime_type));
        $this->set('path', $file_path);
    }

    function chart() {
        /// Status Based on Count
        $this->set('opened_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForFunding,
            )
        )));
		 $this->set('idea_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForIdea,
            )
        )));
        $this->set('pending_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::Pending,
            )
        )));
        $this->set('canceled_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::ProjectCancelled,
            )
        )));
		$this->set('goal_reached', $this->Project->find('count', array(
            'conditions' => array(
                'ProjectStatus.id = ' => ConstProjectStatus::GoalReached,
            )
        )));
		$this->set('reserve_amount_reached', $this->Project->find('count', array(
            'conditions' => array(
                'ProjectStatus.id = ' => ConstProjectStatus::ReserveAmountReached,
            )
        )));


        $this->set('closed_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::FundingClosed,
            )
        )));
		$this->set('open_for_idea', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::OpenForIdea,
            )
        )));

        $this->set('expired_project_count', $this->Project->find('count', array(
            'conditions' => array(
                'Project.project_status_id = ' => ConstProjectStatus::FundingExpired,
            )
        )));
		 $this->set('paid_projects', $this->Project->Transaction->find('count', array(
            'conditions' => array(
                'Transaction.class = ' => 'Project',
                'Transaction.transaction_type_id = ' => ConstTransactionTypes::Project,
            )
        )));
        $this->set('total_projects', $this->Project->find('count'));
    }
    
    public function admin_payment($id = null){
        //do something
        $projectFundsConditions = array(
				'ProjectFund.is_paid' => 1,
                'ProjectFund.project_id' => $id,
            );
		$projectFunds = $this->ProjectFund->find('all', array(
            'conditions' => $projectFundsConditions,
			'fields' => array(
                    'ProjectFund.id',
                    'ProjectFund.pay_key',
                    'ProjectFund.payment_status',
                    'ProjectFund.amount',
					'ProjectFund.is_refunded',
                ) ,
            'recursive' => - 1
        ));
        $this->set('projectFunds', $projectFunds);
    }
    
    public function admin_paymentupdatefund($id = null){
    	if(!isset($_POST['projectFund']))
    		return;
    	
        if(isset($_POST['Refund']))
        	$isUnRefurn = 0;
        else 
        	$isUnRefurn = 1;
        $this->autoRender = false;
        $projectID = $this->Payment->updateRefund($_POST['projectFund'],$isUnRefurn);
        $this->redirect(array(
		    'controller' => 'Projects', 'action' => 'admin_payment', $projectID
		));
    }
}
?>